package com.cema.manage.config;

import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import com.cema.manage.common.utils.DataBaseUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

public class MasterDb {
    public static String BASE_PACKAGE = "";
    public static String XML_PATH = null;
    public static String USER_NAME = null;
    public static String PASSWORD = null;
    public static String DB_URL = null;

    public MasterDb(String url, String userName, String password, String basePackage, String xmlPath) {
        BASE_PACKAGE = basePackage;
        XML_PATH = xmlPath;
        DB_URL = url;
        USER_NAME = userName;
        PASSWORD = password;
    }

    @Primary
    @Bean(
            name = {"masterDataSource"}
    )
    public DataSource masterDataSource() {
        return DataBaseUtils.getDataSources(DB_URL, USER_NAME, PASSWORD);
    }

    @Bean(
            name = {"masterSqlSessionFactory"}
    )
    @Primary
    public MybatisSqlSessionFactoryBean masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
        return DataBaseUtils.getSessionFactory(dataSource, BASE_PACKAGE, XML_PATH);
    }

    @Bean(
            name = {"masterTransactionManager"}
    )
    @Primary
    public DataSourceTransactionManager masterTransactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
